package dof;

import java.awt.Color;

import javax.vecmath.Point3d;
import javax.vecmath.Vector3d;

import lib.common.ColorOperation;
import model.ray.Ray;
import raytracing.RayTracer;
import camera.ThinlensCamera;

public class DephtOfField {
	
	Ray ray;
	RayTracer rayTracer;
	
	public DephtOfField(Ray ray, RayTracer rayTracer) {
		this.ray = ray;
		this.rayTracer = rayTracer;
	}
	
	public int getPixelValue( ) {
		ThinlensCamera camera = (ThinlensCamera)rayTracer.scene.camera;
		//DOF. Fuente: http://cg.skeelogy.com/depth-of-field-using-raytracing/					
		Vector3d DOF_direction = new Vector3d();
		Point3d DOF_starting_point = new Point3d();
		
		double tita = camera.forward.angle(ray.direction);
		double d_prima = camera.imdist / Math.cos(tita);
		
		Point3d Q = new Point3d();
		Q.set(ray.direction);
		Q.scale(d_prima);
		Q.add(camera.eye);
		
		int ray_for_dof = rayTracer.RAYS_FOR_DOF_DEFAULT;
			
		Point3d P = new Point3d();
		double d_segunda = d_prima * camera.fdist / camera.imdist;
		P.set(ray.direction);
		P.scale(d_segunda);
		P.add(camera.eye);
		
		if( rayTracer.scene.isAAEnabled() ) {
			ray_for_dof = rayTracer.scene.image.aa.secondValue * rayTracer.RAYS_FOR_DOF_DEFAULT;
		}

		Color [] listColor = new Color[ray_for_dof];
		Color color = null;

		
		for (int i = 0; i < ray_for_dof; ++i)
		{
			Ray viewRay = new Ray(DOF_starting_point, DOF_direction);
			DOF_starting_point.set(Q);
			if (camera.lensr != 0.0f) {
				Vector3d desviacionRandom = new Vector3d( camera.lensr * Math.random(), camera.lensr * Math.random(), 0.0f);
				DOF_starting_point.add(desviacionRandom);
				viewRay.origin.set(DOF_starting_point);
				
				DOF_direction = new Vector3d();
				DOF_direction.sub(P, DOF_starting_point);
				DOF_direction.normalize();
				viewRay.direction.set(DOF_direction);
				
//				if( aaEnabled ) {
//					AdaptiveSuperSampling adaptiveSuperSampling = new AdaptiveSuperSampligQuadtree(3, viewRay, widthReference, heightReference, tdepth, RayTracer.this );
//					color = adaptiveSuperSampling.pixelValue();
//				} else {
					color = new Color( rayTracer.getColor(viewRay, rayTracer.tdepth.getDepths()));
//				}
				
			}
			listColor[i] = color;
		}
		int colorRGB = ColorOperation.average(listColor).getRGB();
		return colorRGB;
	}
}
